package com.ganzalang.gmall.learning.netty.nio.groupchat;

import io.netty.util.concurrent.DefaultThreadFactory;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static java.lang.Thread.sleep;

/**
 * @description: 群聊系统客户端
 * @author: Ganzalang
 * @Date 2021/7/14 21:53
 */
@Slf4j
public class GroupChatClient {

    // 定义相关属性
    // 服务端ip
    private final String HOST = "127.0.0.1";
    // 服务端端口号
    private final int PORT = 6667;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    // 初始化构造器
    public GroupChatClient() throws IOException {
        // 连接到服务器
        socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
        // 设置非阻塞
        socketChannel.configureBlocking(false);
        selector = Selector.open();
        // 将channel注册到selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        // 得到username
        username = socketChannel.getLocalAddress().toString().substring(1);
        log.info(username + " is ok...");


    }

    /**
     * 向服务器发送消息
     */
    public void sendInfo(String info) {
        info = username + "说："+ info;

        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取从服务器回复的消息
     */
    public void readInfo() {
        try {
            int count = selector.select();

            if (count > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();

                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();

                    if (key.isReadable()) {
                        SocketChannel channel = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        // 读取数据
                        channel.read(buffer);
                        // 把读到缓冲区的数据转成字符串
                        String msg = new String(buffer.array());
                        log.info(msg.trim());
                    }

                iterator.remove();
                }
            } else {
//                log.info("没有可用的通道...");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception{
        // 启动客户端
        GroupChatClient groupChatClient = new GroupChatClient();

        // 创建一个线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(10, 20, 10, TimeUnit.MINUTES, new LinkedBlockingDeque<>(), new DefaultThreadFactory("Server-Pool"));
        // 启动一个线程每隔3秒读取从服务端发来的数据
        threadPoolExecutor.execute(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    groupChatClient.readInfo();
                    try {
                        sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        // 发送数据给服务端
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String msg = scanner.nextLine();
            groupChatClient.sendInfo(msg);
        }

    }
}
